<?php

function loadPluginResource($name){
    //加载语言包
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/lang";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/lang";
    }
    foreach($load as $val){
        lang()->pluginLoader($val);
    }

    //加载配置文件
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/config";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/config";
    }

    foreach($load as $val){
        config()->pluginLoader($val);
    }

    //覆盖-加载配置文件
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/config_cover";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/config_cover";
    }
    foreach($load as $val){
        config()->pluginLoaderCover($val);
    }

    //加载自定义函数
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/helper";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/helper";
    }
    foreach($load as $val){
        pluginHelp($val);
    }

    //加载容器
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/provider";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/provider";
    }
    foreach($load as $val){
        pluginRegisterService($val);
    }

    //加载路由
    $load=array();
    $load[]=LTCMS_ROOT."/plugins/{$name}/route";
    if(defined("LTCMS_APP_NAME")){
        $load[]=LTCMS_ROOT."/plugins/{$name}/".LTCMS_APP_NAME."/route";
    }
    foreach($load as $val){
        pluginRegisterRoute($val);
    }
}

/**
 * 获取货号
 * @return string
 */
function productsNo($pre="")
{
    list($usec, $sec) = explode(" ", microtime());
    $usec = substr(str_replace('0.', '', $usec), 0 ,4);
    $str  = rand(10000,99999);
    return $pre.date("YmdHis").$usec.$str;
}

if (!function_exists('getScriptContent')) {
    /**
     * 获取脚本内容
     */
    function getScriptContent($url)
    {
        return "<script>window.top.location.href='{$url}';</script>";
    }
}

if (!function_exists('noCache')) {
    function noCache()
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
    }
}

if (!function_exists('streamOpen')) {
    function streamOpen()
    {
        ob_end_clean();
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no');
    }
}

if (!function_exists('continueExec')) {
    /**
     * 继续执行
     */
    function continueExec($time = 600)
    {
        ignore_user_abort(true);
        set_time_limit($time);
        ini_set("max_execution_time", $time);
    }
}

if (!function_exists('replaceOssImgUrl')) {
    function replaceOssImgUrl($ossUrl)
    {
        return str_replace("http://qzcn.oss-cn-hangzhou.aliyuncs.com", "https://img.qiuzhicn.com", $ossUrl);
    }
}

if (!function_exists('impulseSender')) {
    /**
     * 发号器
     * @return string
     */
    function impulseSender()
    {
        $md_str = time();
        $md_str .= request()->ip();
        $md_str .= uniqid(mt_rand(), true);
        $md_str .= rand(10000, 99999);
        $charid = strtoupper(md5($md_str));
        return $charid;
    }
}

if (!function_exists('dict')) {
    /**
     * 获取字段对象
     * @return ArrayObject
     */
    function dict()
    {
        return new ArrayObject();
    }
}

if (!function_exists('parseToArr')) {
    /**
     * 把数据转换成数组
     * @param $param
     * @return array|mixed|string
     */
    function parseToArr($param, $key = "", $default = "")
    {
        if ($param) {
            if (is_object($param)) {
                $result = objToArray($param);
            } else {
                $result = $param;
            }
            if ($key) {
                return isset($result[$key]) ? $result[$key] : $default;
            } else {
                return $result;
            }
        } else {
            return $default;
        }
    }
}

if (!function_exists('objToArray')) {
    /**
     * 将对象转换成数组
     * @param $obj
     * @return mixed
     */
    function objToArray($obj)
    {
        return json_decode(json_encode($obj), true);
    }
}

if (!function_exists('blenderObject')) {
    /**
     * 融合两个对象，后面覆盖前面的数据，数组进行融合不完全覆盖。
     */
    function blenderObject($objOne, $objTwo)
    {
        if (!empty($objTwo)) {
            $objOneArr = (array)$objOne;
            $objTwoArr = (array)$objTwo;
            foreach ($objTwoArr as $key => $val) {
                if (isset($objOneArr[$key])) {
                    if (is_array($objOneArr[$key])) {
                        if (is_array($val)) {
                            $objOneArr[$key] = blenderObject($objOneArr[$key], $val);
                        } else {
                            $objOneArr[$key] = $val;
                        }
                    } else {
                        $objOneArr[$key] = $val;
                    }
                } else {
                    $objOneArr[$key] = $val;
                }
            }
            return (object)$objOneArr;
        } else {
            return $objOne;
        }
    }
}

if (!function_exists('mergeArr')) {
    /**
     * 融合两个数组，后面覆盖前面的数据，数组进行融合不完全覆盖。
     */
    function mergeArr($objOne, $objTwo)
    {
        if (!empty($objTwo)) {
            $objOneArr = $objOne;
            $objTwoArr = $objTwo;
            foreach ($objTwoArr as $key => $val) {
                if (isset($objOneArr[$key])) {
                    if (is_array($objOneArr[$key])) {
                        if (is_array($val)) {
                            $objOneArr[$key] = mergeArr($objOneArr[$key], $val);
                        } else {
                            $objOneArr[$key] = $val;
                        }
                    } else {
                        $objOneArr[$key] = $val;
                    }
                } else {
                    $objOneArr[$key] = $val;
                }
            }
            return $objOneArr;
        } else {
            return $objOne;
        }
    }
}

if (!function_exists('paramsObj')) {
    function paramsObj()
    {
        return new stdClass();
    }
}

if (!function_exists('toJsonEncode')) {
    function toJsonEncode($data, $default = "")
    {
        if (empty($data)) {
            return $default;
        } else {
            return json_encode($data, JSON_UNESCAPED_UNICODE);
        }
    }
}

if (!function_exists('toJsonDecode')) {
    function toJsonDecode($data, $default = "")
    {
        if (empty($data)) {
            return $default;
        } else {
            return json_decode($data, true);
        }
    }
}

if (!function_exists('trim_deep')) {
    /**
     * 去除数组中的空格
     * @param $value
     * @return array|string
     */
    function trim_deep($value)
    {
        if (is_array($value)) {
            $value = array_map("trim_deep", $value);
        } else {
            if (!is_null($value) && !is_numeric($value) && !is_bool($value)) {
                $value = trim($value);
            }
        }
        return $value;
    }
}


if (!function_exists('getParamsObj')) {
    /**获取有默认通用的参数对象
     * @param $paramObj //需要继承的 参数对象
     * @param $mixed // 1 数据混合
     * @param $messages //验证提示数组
     * @param $rules //验证规则数组
     * @param $dataDefault //默认信息数组
     * @return mixed|object|stdClass
     */
    function getParamsObj( $paramObj = null,$params = [], $mixed = 1, $rules = [], $messages = [], $dataDefault = [])
    {
        $paramsObj = paramsObj();  //获取空对象
        $paramsObj->mixed = $mixed;        //数据混合,用户提交的数据,覆盖默认数据
        $paramsObj->messages = $messages;       //设置消息提示
        $paramsObj->rules = $rules;  //设置用的验证规则  和需要的参数
        $paramsObj->dataDefault = $dataDefault; //设置默认信息
        $paramsObj->data = paramsObj();
        $paramsObj->data->use_trans = false;   //是否使用了事务
        $paramsObj->params = $params;
        $paramsObj->result = []; //验证参数后信息存放
        $paramsObj->noFilter = array(); //不进行过滤的字段名 ,解决参数会被强制url解码的问题
        if ($paramObj != null) {
            $paramsObj = blenderObject($paramsObj, $paramObj); //合并对象后面覆盖前面的数据，数组进行融合不完全覆盖。
        }

        return $paramsObj;
    }
}

if (!function_exists('LTcmsTag')) {
    /**
     * 自定义标签
     */
    function LTcmsTag($tagName, $params,$extra=array())
    {
        //过滤参数
        $filterParams = app("P_tag_plugin")->filterParams($params,$extra);
        $tagResult = array();
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "tagName" => $tagName,
            "extraData" => $filterParams["condition"],
        );
        $checkResult = app("P_tag_plugin")->run($paramsObj);
        if ($checkResult["error_no"] == 0) {
            $tagResult = $checkResult["result"];
        } else {
            recordErrorLog($checkResult); //记录错误信息
        }

        $key = isset($filterParams["sysParam"]["key"]) ? $filterParams["sysParam"]["key"] : "key";
        $val = isset($filterParams["sysParam"]["val"]) ? $filterParams["sysParam"]["val"] : "field";
        $render = getVal($tagResult,"render");
        $row = getVal($tagResult,"row");
        $receiveName = isset($filterParams["sysParam"]["receiveName"]) ? $filterParams["sysParam"]["receiveName"] : "";
        $noneStr = isset($filterParams["sysParam"]["noneStr"]) ? $filterParams["sysParam"]["noneStr"] : "";
        $return = array();
        $return["sysParam"] = array(
            "key" => $key,
            "val" => $val,
            "render" => $render,
            "row" => $row,
            "receiveName" => $receiveName,
            "noneStr" => $noneStr,
        );
        $return["data"] = getVal($tagResult,"result");
        return $return;
    }
}

if (!function_exists('varReplaceV2')) {
    /**
     * 变量替换
     */
    function varReplaceV2($params)
    {
        $reg = "/<([^>]+)>/";
        $ok = preg_match_all($reg, $params, $matachs);
        if ($ok > 0) {
            $search = $matachs[0];
            $replace = array();
            $findData = isset($matachs[1]) ? $matachs[1] : "";
            if ($findData) {
                foreach ($findData as $fval) {
                    $tmpMap = explode(".", $fval);
                    $varName = "";
                    $varAttr = array();
                    foreach ($tmpMap as $key => $val) {
                        if ($key == "0") {
                            $varName = $val;
                        } else {
                            $varAttr[] = "['{$val}']";
                        }
                    }
                    $tmpReplace = $varName . implode("", $varAttr);
                    $tmpReplace = "{\$$tmpReplace}";
                    $replace[] = $tmpReplace;
                }
                $params = str_replace($search, $replace, $params);
            }
        }
        return $params;
    }
}

if (!function_exists('varReplace')) {
    /**
     * 变量替换
     */
    function varReplace($params)
    {
        $needReg = "/EOD(.+?)EOD/s";
        //匹配出需要替换的地方
        $needOk = preg_match_all($needReg, $params, $needMatachs);
        if ($needOk > 0) {
            $needSearch = $needMatachs[0];
            $needReplace = $needMatachs[0];
            $needHandleData = isset($needMatachs[1]) ? $needMatachs[1] : "";
            if ($needHandleData) {
                foreach ($needHandleData as $fnval) {
                    $reg = "/<([^>]+)>/";
                    $ok = preg_match_all($reg, $fnval, $matachs);
                    if ($ok > 0) {
                        $search = $matachs[0];
                        $replace = array();
                        $findData = isset($matachs[1]) ? $matachs[1] : "";
                        if ($findData) {
                            foreach ($findData as $fval) {
                                $tmpMap = explode(".", $fval);
                                $varName = "";
                                $varAttr = array();
                                foreach ($tmpMap as $key => $val) {
                                    if ($key == "0") {
                                        $varName = $val;
                                    } else {
                                        $varAttr[] = "['{$val}']";
                                    }
                                }
                                $tmpReplace = $varName . implode("", $varAttr);
                                $tmpReplace = "{\$$tmpReplace}";
                                $replace[] = $tmpReplace;
                            }
                            $needReplace = str_replace($search, $replace, $needReplace);
                        }
                    }
                }
            }
            $params = str_replace($needSearch, $needReplace, $params);
        }
        return $params;
    }
}

if (!function_exists('parseHtml')) {
    /**
     * 解析html
     * @param $data
     * @return string
     */
    function parseHtml($data)
    {
        return htmlspecialchars_decode($data);
    }
}

if (!function_exists('getListUrlRule')) {
    /**
     * 获取url规则
     * @param $value
     * @return array|string
     */
    function getListUrlRule()
    {
        $moduleListHtml = extendSetting("listHtml");
        if (is_numeric($moduleListHtml)) {
            $fileExtension = siteSetting("fileExtension");
            $prefix = "";
            if ($moduleListHtml == "1") {
                $listUrlRule = extendSetting("htmlListUrlRule");
                $prefix = extendSetting("htm_list_prefix");
                $rule = config("setting_data.listUrlRule.htm.list.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.htm.list.{$listUrlRule}.page");
            } else {
                $listUrlRule = extendSetting("listUrlRule");
                $rule = config("setting_data.listUrlRule.php.list.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.php.list.{$listUrlRule}.page");
            }
            $replace = array(
                "prefix" => $prefix,
                "file_ext" => $fileExtension,
            );
            $rule = urlRuleReplace($replace, $rule);
            $rulePage = urlRuleReplace($replace, $rulePage);
        } else {
            $rule = null;
            $rulePage = null;
        }
        return array(
            "rule" => $rule,
            "rulePage" => $rulePage,
        );
    }
}

if (!function_exists('getItemUrlRule')) {
    /**
     * 获取url规则
     * @param $value
     * @return array|string
     */
    function getItemUrlRule()
    {
        $moduleListHtml = extendSetting("conHtml");
        if (is_numeric($moduleListHtml)) {
            $fileExtension = siteSetting("fileExtension");
            $prefix = "";
            if ($moduleListHtml == "1") {
                $listUrlRule = extendSetting("htmlConUrlRule");
                $prefix = extendSetting("htm_item_prefix");
                $rule = config("setting_data.listUrlRule.htm.item.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.htm.item.{$listUrlRule}.page");
            } else {
                $listUrlRule = extendSetting("conUrlRule");
                $rule = config("setting_data.listUrlRule.php.item.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.php.item.{$listUrlRule}.page");
            }
            $replace = array(
                "prefix" => $prefix,
                "file_ext" => $fileExtension,
            );
            $rule = urlRuleReplace($replace, $rule);
            $rulePage = urlRuleReplace($replace, $rulePage);
        } else {
            $rule = null;
            $rulePage = null;
        }
        return array(
            "rule" => $rule,
            "rulePage" => $rulePage,
        );
    }
}

if (!function_exists('getModuleListUrlRule')) {
    /**
     * 获取模型url规则
     * @param $value
     * @return array|string
     */
    function getModuleListUrlRule($pid, $replaceArr = array())
    {
        $moduleListHtml = setting("moduleListHtml", $pid);
        if (is_numeric($moduleListHtml)) {
            $fileExtension = siteSetting("fileExtension");
            $prefix = "";
            if ($moduleListHtml == "1") {
                $listUrlRule = setting("htmlListUrlRule", $pid);
                $prefix = setting("htm_list_prefix", $pid);
                $rule = config("setting_data.listUrlRule.htm.list.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.htm.list.{$listUrlRule}.page");
            } else {
                $listUrlRule = setting("listUrlRule", $pid);
                $rule = config("setting_data.listUrlRule.php.list.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.php.list.{$listUrlRule}.page");
            }

            $replace = array(
                "prefix" => $prefix,
                "file_ext" => $fileExtension,
            );
            if ($replaceArr) {
                $replace = array_merge($replace, $replaceArr);
            }
            $rule = urlRuleReplace($replace, $rule);
            $rulePage = urlRuleReplace($replace, $rulePage);
        } else {
            $rule = null;
            $rulePage = null;
        }
        return array(
            "rule" => $rule,
            "rulePage" => $rulePage,
        );
    }
}

if (!function_exists('getModuleItemUrlRule')) {
    /**
     * 获取模型url规则
     * @param $value
     * @return array|string
     */
    function getModuleItemUrlRule($pid, $replaceArr = array())
    {
        $moduleListHtml = setting("moduleConHtml", $pid);
        if (is_numeric($moduleListHtml)) {
            $fileExtension = siteSetting("fileExtension");
            $prefix = "";
            if ($moduleListHtml == "1") {
                $listUrlRule = setting("htmlConUrlRule", $pid);
                $prefix = setting("htm_item_prefix", $pid);
                $rule = config("setting_data.listUrlRule.htm.item.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.htm.item.{$listUrlRule}.page");
            } else {
                $listUrlRule = setting("conUrlRule", $pid);
                $rule = config("setting_data.listUrlRule.php.item.{$listUrlRule}.index");
                $rulePage = config("setting_data.listUrlRule.php.item.{$listUrlRule}.page");
            }
            $replace = array(
                "prefix" => $prefix,
                "file_ext" => $fileExtension,
            );
            if ($replaceArr) {
                $replace = array_merge($replace, $replaceArr);
            }
            $rule = urlRuleReplace($replace, $rule);
            $rulePage = urlRuleReplace($replace, $rulePage);
        } else {
            $rule = null;
            $rulePage = null;
        }
        return array(
            "rule" => $rule,
            "rulePage" => $rulePage,
        );
    }
}

if (!function_exists('moduleLinkUrl')) {
    function moduleLinkUrl($Result)
    {
        $linkUrl = "";
        if (isset($Result['domain_mobile']) && isset($Result['domain_pc']) && isset($Result['isLink']) && isset($Result['linkUrl']) && isset($Result['urlPath'])) {
            $linkUrl = $Result['linkUrl'];
            if ($Result['isLink'] == "0") {
                if (is_mob()) {
                    $domain_mobile = $Result['domain_mobile'];
                    if ($domain_mobile) {
                        $linkUrl = rtrim($domain_mobile, "/") . "/" . $Result['urlPath'] . "/";
                    }
                } else {
                    $domain_pc = $Result['domain_pc'];
                    if ($domain_pc) {
                        $linkUrl = rtrim($domain_pc, "/") . "/" . $Result['urlPath'] . "/";
                    }
                }
            }
        }
        return $linkUrl;
    }
}

if (!function_exists('categoryLinkUrl')) {
    function categoryLinkUrl($Result)
    {
        $linkUrl = "";
        if (isset($Result["dataType"]) && isset($Result["linkurl"]) && isset($Result["dataId"])) {
            $moduleData = module($Result["dataId"]);
            $linkUrl = $moduleData["linkUrl"] . $Result["linkurl"];
        }
        return $linkUrl;
    }
}

if (!function_exists('urlRuleReplace')) {
    function urlRuleReplace($replace, $rule)
    {
        $search = array();
        foreach ($replace as $key => $val) {
            $search[] = '{$' . $key . '}';
        }
        $result = str_replace($search, $replace, $rule);
        return $result;
    }
}

if (!function_exists('arrToUrlPrarm')) {
    function arrToUrlPrarm($array,$mark=true)
    {
        $prarms = arrToUrlMap($array);
        $mark=$mark?"?":"";
        return $prarms?$mark.implode("&", $prarms):"";
    }
}

if (!function_exists('urlQueryStr')) {
    function urlQueryStr($prarms,$mark=true)
    {
        $mark=$mark?"?":"";
        return $prarms?$mark.implode("&", $prarms):"";
    }
}

if (!function_exists('formatQuery')) {
    function formatQuery($array)
    {
        $prarms = [];
        foreach ($array as $key => $val) {
            if(is_array($val)){
                foreach($val as $zkey=>$zval){
                    $tmp_key=$key."[{$zkey}]";
                    $prarms[$tmp_key] = $zval;
                }
            }else{
                $prarms[$key] = $val;
            }
        }
        return $prarms;
    }
}

if (!function_exists('arrToUrlMap')) {
    function arrToUrlMap($array)
    {
        $prarms = [];
        foreach ($array as $key => $val) {
            if(is_array($val)){
                foreach($val as $zkey=>$zval){
                    $prarms[] = $key."[{$zkey}]" ."=".$zval;
                }
            }else{
                $prarms[] = $key ."=".$val;
            }
        }
        return $prarms;
    }
}

if (!function_exists('ltcmsLoginInfo')) {
    function ltcmsLoginInfo()
    {
        $runtime=runtimePath();
        $loginFile=$runtime."login_file";
        if(is_file($loginFile)){
            $loginData=file_get_contents($loginFile);
            $loginData=$loginData?toJsonDecode($loginData):array();
        }else{
            $loginData=array();
        }
        return $loginData;
    }
}

if (!function_exists('dsubstr')) {
    function dsubstr($string, $length, $suffix = '', $start = 0) {
        if($start) {
            $tmp = dsubstr($string, $start);
            $string = substr($string, strlen($tmp));
        }
        if(!$suffix){
            $suffix="";
        }
        $strlen = strlen($string);
        if($strlen <= $length) return $string;
        $string = str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $string);
        $length = $length - strlen($suffix);
        $str = '';
        if(strtolower(LTCMS_CHARSET) == 'utf-8') {
            $n = $tn = $noc = 0;
            while($n < $strlen)	{
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t <= 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if($noc >= $length) break;
            }
            if($noc > $length) $n -= $tn;
            $str = substr($string, 0, $n);
        } else {
            for($i = 0; $i < $length; $i++) {
                $str .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
            }
        }
        $str = str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $str);
        return $str == $string ? $str : $str.$suffix;
    }
}

if (!function_exists('phpVersionCompare')) {
    /**
     * php版本比较
     */
    function phpVersionCompare($version2,$operator="=")
    {
        $version1=phpversion();
        $ok=version_compare($version1,$version2,strtolower($operator));
        return $ok;
    }
}

if (!function_exists('getTable')) {
    /**
     * 获取表名
     */
    function getTable($moduleId, $data = 0)
    {
        $module=module($moduleId,"module");
        if($module){
            $table=array();
            $db_pre=app("cmsTable")::getPre();
            if($data) {
                return in_array($module, $table) ? $db_pre.$module.'_data' : $db_pre.$module.'_data_'.$moduleId;
            } else {
                return in_array($module, $table) ? $db_pre.$module : $db_pre.$module.'_'.$moduleId;
            }
        }
        return "";
    }
}

if (!function_exists('fileLastLines')) {
    /**
     * 取文件最后$n行
     * @param string $filename 文件路径
     * @param int $n 最后几行
     * @return mixed false表示有错误，成功则返回字符串
     */
    function fileLastLines($filename,$n){
        if(!is_file($filename)){
            return false;
        }
        if(!$fp=fopen($filename,'r')){
            return false;
        }
        $pos=-2;
        $eof="";
        $str=array();
        while($n>0){
            while($eof!="\n"){
                if(!fseek($fp,$pos,SEEK_END)){
                    $eof=fgetc($fp);
                    $pos--;
                }else{
                    break;
                }
            }
            $str[]=fgets($fp);
            $eof="";
            $n--;
        }
        return array_reverse($str);
    }
}

if(!function_exists("sortByLength")){
    /**
     * 按长度排序
     * @param $a
     * @param $b
     * @return int
     */
    function sortByLength($a, $b) {
        return strlen($b) - strlen($a);
    }
}
